import { useCallback, useEffect, useState } from 'react';
import AddModal from '../../components/AddModal';
import useRouter from '../../hooks/useRouter';
import { deleteGood, GoodProps, queryGoodsList } from '../../api';


function Index() {
  const [items, setItems] = useState<GoodProps[] | undefined>();
  const [visible, setVisible] = useState<boolean>(false)
  const [id, setId] = useState<string>()
  const { navigate } = useRouter()

  const getData = useCallback(() => {
    queryGoodsList().then(data => {
      console.log(data)
      setItems(data);
    })

  }, [])

  useEffect(() => {
    getData()
  }, [getData]);

  const handleDel = (id: string) => {
    deleteGood(id).then(data => {
      console.log(data)
      getData()
    })
  }

  const onClose = () => {
    setId('')
    setVisible(false)
  }

  const onModify = (id: string) => {
    setId(id)
    setVisible(true)
  }

  const handleToFlask = () => {
    navigate('/login')
  }

  return (
    <div className="App">
      <div>跳转到：<button onClick={handleToFlask}>go to flask</button></div>
      <div>list:</div>
      <ul>
        {items && items.map(item => (
          <li key={item.id}>
            {item.name}: {item.description}
            <button onClick={() => handleDel(item.id)}>删除</button>
            <button onClick={() => onModify(item.id)}>修改</button>
          </li>
        ))}
      </ul>
      <button onClick={() => setVisible(true)}>添加</button>
      <AddModal id={id} visible={visible} onSucess={getData} onClose={onClose} />
    </div>
  );
}

export default Index;
